/* 
 * 
 */


function assignDialog(item) {        
    // Create and load the content of the login dialog, then make it a dialog
    tempDialog = $('<div></div>').load('dialogs/assignProject.php', function () {  
        
        var projectName = document.getElementById('projectNameAssign');     // get tag to display projectname
        var groupName = document.getElementById('groupNameAssign');         // get tag to display group name
        projectName.innerHTML = document.getElementById('proNameDialog').innerHTML; // get projectname
        groupName.innerHTML = item.parentNode.parentNode.firstChild.id;         //get group name
        // Run this code when the content of the dialog has loaded                          
        // When the log in button is pressed, run the login method
        
        $('form.assignProject input[name="searchteacher"]').click (function() {
            searchTeacher();        // onclick event to search for teachers
        });        
            
        $('form.assignProject input[name="acceptAssign"]').click (function() {
            if(assignProject(item)) {   // assign a project a group and advisors
                tempDialog.dialog('close'); // if success then close dialog
            }            
        });
        // Open the login dialog        
        tempDialog.dialog('open');
    }).dialog({
        autoOpen: false,
        position: [500,200],
        width: 400,
        title: 'Tildel en gruppe dette prosjektet og tildel prosjektet en veileder',
        close: function (event, ui) {   // add close event
            $(this).remove();
            $('body > section').load ('pages/viewGroupsPriority.php');
        }
    });    
    // Find the dialog and open it (Note, this doesn't work when creating the dialog on the fly so we need both)
    $('.assignProject').parent().dialog('open');    
}

/*
 * This function search for a person in tvils db and adds it to the dialog
 */
function searchTeacher() {    
    var name = document.getElementById('searchteacher').value;  // get user input
    $.ajax ({
        url : 'https://tvil.hig.no/json_services/searchUser.php',
        data : {
            'search': name
        },
        crossDomain : true,
        type : 'POST',
        dataType : 'json',
        success : function (data) {
            if (data.error!=null) { // if didnt find student
                $('#students').append('<h3>Ingen studenter med navn '+search+' funnet!</h3>');
            } else {
                for (i in data) { // loops trough the teachers found
                    var array = new Array(); // creates a temp array
                    var employee = false    // ansatt check
                    for (e in data[i]) { // loop trough the info
                        array.push(data[i][e]); // puts userinfo in an array
                        if(e == "employee" && data[i][e] == "y"){   // if employee
                            employee = true;                    // then set flag
                        }
                    }
                    if(employee == true) {              // if flag is true then display search result
                        
                        $('#assignList').append('<li id="'+array[0]+'"><img src="LnF/check_24x20.png" height="13" onclick="assignTeacher(this);" ><span>'+array[1]+' '+array[2]+'</span></li>');
                    }                
                }
            }
        }
    });
}

/*
 * This function assigns a project two advisors
 */
function assignTeacher(item, number) {
    var assign = document.getElementById('listAssigned'); // get selected teachers as advisors
    parent = item.parentNode;                             // get list tag
    if(assign.getElementsByTagName('li').length == 0){      // if non advisors is selected add first advisor
        parent.innerHTML = '<img src="LnF/x_21x21.png" height="13" onclick="removeTeacher(this);" >Veileder 1: ' + item.nextSibling.innerHTML;
    }else if(assign.getElementsByTagName('li').length == 1) {   // if one advisor is selected then add second
        parent.innerHTML = '<img src="LnF/x_21x21.png" height="13" onclick="removeTeacher(this);" >Veileder 2: ' + item.nextSibling.innerHTML;
    } else {
        alert("Kan ikke legge til flere veiledere!"); // you cant add more than two advisors
        return;
    }    
    assign.appendChild(parent);         // append the list tag to dialog
}


/*
 * This function removes the list tag that displays a selected advisor
 */
function removeTeacher(item) {
    item.parentNode.parentNode.removeChild(item.parentNode);
}

/*
 * This function assigns a project a group and two advisors in the database and send email to all
 */
function assignProject(item) {
    var projectId = item.parentNode.id; // get project id
    var groupId = item.parentNode.parentNode.id;    // get group id
    var assign = document.getElementById('listAssigned');   // get advisor list 
    var teachers = assign.getElementsByTagName('li');       // get advisor display tag
    if(teachers.length < 2) {                           // if not enough advisors
        alert("Mangler veileder(e)!");
        return false;
    }
    var name1 = teachers[0].id;         // set advisor 1
    var name2 = teachers[1].id;         // set advisor 2
    $.ajax ({
        url : 'higface/employee/library/assignProject.php',
        type : 'POST',
        data: {
            adv1: name1,
            adv2: name2,
            proid: projectId,
            grpid: groupId
        },
        success : function (tmp) {
            data = eval ('('+tmp+')');
            var string = data[0][0]+', ';   // add external users email to string
            for(g=0; g<data.length;g++){        //loops trough the students
                var temp=0;
                getUser(data[g][1], function(stud) {  // get student info(email)          
                    temp++;
                    if(temp == data.length){        // if end of loop
                        string += stud[3];          // add last student and send mail
                        sendMail("Prosjektet \""+data[0][2]+"\" har blitt tildelt gruppen "+data[0][3], string);
                        return;
                    }
                    string += stud[3]+', '; // add student mail to string
                });
            }                        
        }
    });
    return true; // return true to close the dialog
}